package DB;

import java.util.ArrayList;
import java.util.Date;

import org.lightcouch.CouchDbClient;

import com.google.gson.JsonObject;

public class GroupAndUsersTableDB {
	private CouchDbClient dbClient;
	
	public static final String IDCOL = "_id";
	public static final String GROUPFK = "groupid";
	public static final String USERFK = "userid";
	public static final String GROUPSANDUSERS = "groupsandusers";
	
	public GroupAndUsersTableDB(){
		dbClient =  new CouchDbClient(GROUPSANDUSERS, true, "http", "127.0.0.1", 5984, null, null);
	}
	
	public String createGroupAndUsers(String userID, String groupID){
		JsonObject object = new JsonObject();
		String id = String.valueOf(new Date().getTime() + new Date().getTime());
		object.addProperty(IDCOL, id);
		object.addProperty(USERFK, userID);
		object.addProperty(GROUPFK, groupID);
		// save the message
		dbClient.save(object);
		return "success";
	}
	
	public String deleteGroupAndUsers(String userID, String groupID){
		System.out.println(userID);
		System.out.println(groupID);
		ArrayList<JsonObject> allDocs = (ArrayList<JsonObject>) dbClient.view("_all_docs").includeDocs(true).query(JsonObject.class);
		for(JsonObject json : allDocs){
			if(json.get(GROUPFK).getAsString().equals(groupID) && json.get(USERFK).getAsString().equals(userID)){
				dbClient.remove(json);
			}
		}		
		return "success";
	}
	public String deleteGroupAndUsersByUser(String userID){
		ArrayList<JsonObject> allDocs = (ArrayList<JsonObject>) dbClient.view("_all_docs").includeDocs(true).query(JsonObject.class);
		for(JsonObject json : allDocs){
			if(json.get(USERFK).getAsString().equals(userID)){
				dbClient.remove(json);
			}
		}		
		return "success";
	}
	public String deleteGroupAndUsersByGroup(String groupID){
		ArrayList<JsonObject> allDocs = (ArrayList<JsonObject>) dbClient.view("_all_docs").includeDocs(true).query(JsonObject.class);
		for(JsonObject json : allDocs){
			if(json.get(GROUPFK).getAsString().equals(groupID)){
				dbClient.remove(json);
			}
		}		
		return "success";
	}
	
	public ArrayList<JsonObject> selectGroupAndUsersByGroup(String groupID){
		ArrayList<JsonObject> result = new ArrayList<JsonObject>();
		ArrayList<JsonObject> allDocs = (ArrayList<JsonObject>) dbClient.view("_all_docs").includeDocs(true).query(JsonObject.class);
		for(JsonObject json : allDocs){
			if(json.get(GROUPFK).getAsString().equals(groupID) ){
				result.add(json);
			}
		}
		return result;
	}
	
	public ArrayList<JsonObject> selectGroupAndUserByUser(String userID){
		ArrayList<JsonObject> result = new ArrayList<JsonObject>();
		ArrayList<JsonObject> allDocs = (ArrayList<JsonObject>) dbClient.view("_all_docs").includeDocs(true).query(JsonObject.class);
		for(JsonObject json : allDocs){
			if(json.get(USERFK).getAsString().equals(userID)){
				result.add(json);
			}
		}
		return result;
	}
}
